//
//  EditTagsViewController.m
//  suRead
//
//  Created by lidi on 2018/1/3.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "EditTagsViewController.h"
#import "XWCell.h"
#import "XWHeader.h"
#import "XWDragCellCollectionView.h"
#import "M_tags.h"
#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "AccountManager.h"

@interface EditTagsViewController ()<XWDragCellCollectionViewDataSource, XWDragCellCollectionViewDelegate>
@property(nonatomic,strong)NSArray *allTags;
@property (nonatomic, strong) NSArray *currentTags;
@property (nonatomic, weak) XWDragCellCollectionView *mainView;
@property (nonatomic,copy) EditCompleteHandle handle;
@end

@implementation EditTagsViewController

- (instancetype)initWithTags:(NSArray *)tags handle:(EditCompleteHandle)handle_ {
    if (self = [super init]) {
        self.allTags = tags;
        self.handle = handle_;
    }
    return  self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //编辑区域
    NSArray *t = [AccountManager sharedAccountManager].f_userTags;
    if (t && [t count] > 0) {
        NSMutableArray *other = [NSMutableArray array];
        for (M_tags *item in self.allTags) {
            if (![t containsObject:item]) {
                [other addObject:item];
            }
        }
        self.currentTags = @[t,other];
    } else {
        self.currentTags = @[self.allTags,@[]];
    }
    
    //头部
    __weak typeof(self) weak_self = self;
    
    UIView *navigationBarView = [UIView new];
    navigationBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navigationBarView];
    [navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(navigationBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIView *titleViewContainer = [UIView new];
    [navigationBarView addSubview:titleViewContainer];
    [titleViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(titleViewContainer.superview);
        make.height.equalTo(@44.0f);
    }];
    
    //标题
    UILabel *labelTitle = [UILabel new];
    labelTitle.textColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    labelTitle.text = @"栏目管理";
    labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    [titleViewContainer addSubview:labelTitle];
    [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labelTitle.superview).offset(10.0f);
        make.center.equalTo(labelTitle.superview);
    }];
    
    //返回
    UIButton *buttonReport = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonReport.titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:16.0f];
    [buttonReport setTitle:@"保存" forState:UIControlStateNormal];
    [buttonReport setBackgroundColor:[[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1]];
    buttonReport.layer.cornerRadius = 10.0f;
    buttonReport.layer.masksToBounds = YES;
    
    [buttonReport addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //保存tags
        [AccountManager sharedAccountManager].f_userTags = weak_self.currentTags[0];
        if (weak_self.handle) {
            weak_self.handle(weak_self.currentTags[0]);
        }
        [weak_self.navigationController popViewControllerAnimated:true];
    }];
    
    [titleViewContainer addSubview:buttonReport];
    [buttonReport mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(buttonReport.superview).offset(-10.0f);
        make.centerY.equalTo(buttonReport.superview);
        make.size.mas_equalTo(CGSizeMake(60.0f, 30.0f));
    }];
    
    //底部横线
    UIView *bottomLine = [UIView new];
    bottomLine.backgroundColor = [UIColor lightGrayColor];
    [titleViewContainer addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomLine.superview);
        make.height.equalTo(@.5f);
    }];
    
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    CGFloat width = (self.view.bounds.size.width - 50.0f) / 4.0f;
    layout.itemSize = CGSizeMake(width, 35.0f);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumInteritemSpacing = 10;
    layout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 50.0f);
    CGRect contentFrame = CGRectMake(0, 44.0, self.view.bounds.size.width, self.view.bounds.size.height);
    if (@available(iOS 11.0, *)) {
        contentFrame = CGRectMake(0, 64.0, self.view.bounds.size.width, self.view.bounds.size.height);
    }
    
    if(IS_IOS_9) {
        contentFrame = CGRectMake(0, 64.0, self.view.bounds.size.width, self.view.bounds.size.height);
    }
    
    XWDragCellCollectionView *mainView = [[XWDragCellCollectionView alloc] initWithFrame:contentFrame collectionViewLayout:layout];
    _mainView = mainView;
    mainView.delegate = self;
    mainView.dataSource = self;
    mainView.shakeWhenMoveing = NO;
    mainView.minimumPressDuration = 0.3f;
    mainView.backgroundColor = [UIColor whiteColor];
    [mainView registerNib:[UINib nibWithNibName:@"XWCell" bundle:nil] forCellWithReuseIdentifier:@"XWCell"];
    [mainView registerNib:[UINib nibWithNibName:@"XWHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XWHeader"];
    [self.view addSubview:mainView];
    [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo(navigationBarView.mas_bottom);
        if (iPhoneX) {
            make.bottom.equalTo(self.view).offset(-34.0f);
        } else {
            make.bottom.equalTo(self.view);
        }
    }];
    
}

#pragma mark - <XWDragCellCollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.currentTags count];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *items = self.currentTags[section];
    return [items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XWCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XWCell" forIndexPath:indexPath];
    
    cell.imageViewTag.hidden = NO;

    if (indexPath.section == 0 && indexPath.item < 4) {
        cell.container.backgroundColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
        cell.label.textColor = [UIColor whiteColor];
        cell.imageViewTag.hidden = YES;
    } else {
        cell.container.backgroundColor = [UIColor whiteColor];
        cell.label.textColor = [UIColor blackColor];
    }
    cell.container.layer.cornerRadius = 3.0f;
    cell.container.layer.borderColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1].CGColor;
    cell.container.layer.borderWidth = 0.5f;
    cell.container.layer.masksToBounds = YES;
    M_tags *item = self.currentTags[indexPath.section][indexPath.item];
    cell.label.text = item.f_catName;
    
    if (indexPath.section == 0 && indexPath.item >= 4) {
        cell.imageViewTag.image = [UIImage imageNamed:@"button_tag_del"];
    }
    
    if (indexPath.section == 1) {
        cell.imageViewTag.image = [UIImage imageNamed:@"button_tag_add"];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        XWHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XWHeader" forIndexPath:indexPath];
        [header setType:indexPath.section];
        return header;
    } else {
        return nil;
    }
}

- (NSArray *)dataSourceArrayOfCollectionView:(XWDragCellCollectionView *)collectionView {
    return self.currentTags;
}

#pragma mark - <XWDragCellCollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0 && indexPath.item >= 4) {
        //移除已经订阅的栏目
        NSMutableArray *current = [NSMutableArray arrayWithArray:self.currentTags[0]];
        NSMutableArray *other = [NSMutableArray arrayWithArray:self.currentTags[1]];
        [other addObject:current[indexPath.item]];
        [current removeObjectAtIndex:indexPath.item];
        self.currentTags = @[current,other];
        [AccountManager sharedAccountManager].f_userTags = self.currentTags[0];
        [self.mainView reloadData];
    }
    if (indexPath.section == 1) {
        //添加栏目
        NSMutableArray *current = [NSMutableArray arrayWithArray:self.currentTags[0]];
        NSMutableArray *other = [NSMutableArray arrayWithArray:self.currentTags[1]];
        [current addObject:other[indexPath.item]];
        [other removeObjectAtIndex:indexPath.item];
        self.currentTags = @[current,other];
        [AccountManager sharedAccountManager].f_userTags = self.currentTags[0];
        [self.mainView reloadData];
    }
}

- (void)dragCellCollectionView:(XWDragCellCollectionView *)collectionView newDataArrayAfterMove:(NSArray *)newDataArray{
    self.currentTags = newDataArray;
    [AccountManager sharedAccountManager].f_userTags = self.currentTags[0];
}

- (NSArray<NSIndexPath *> *)excludeIndexPathsWhenMoveDragCellCollectionView:(XWDragCellCollectionView *)collectionView {
    //每个section的最后一个cell都不能交换
    NSMutableArray * excluedeIndexPaths = [NSMutableArray arrayWithCapacity:self.currentTags.count];
    [self.currentTags enumerateObjectsUsingBlock:^(NSArray*  _Nonnull section, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 0) {
            for (NSInteger i=0; i<4; i++) {
                [excluedeIndexPaths addObject:[NSIndexPath indexPathForItem:i inSection:idx]];
            }
        } else {
            for (NSInteger i=0; i<section.count; i++) {
                [excluedeIndexPaths addObject:[NSIndexPath indexPathForItem:i inSection:idx]];
            }
        }
    }];
    return excluedeIndexPaths.copy;
}

@end
